package com.starblink.library.widget.subscription

import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.createViewModelLazy
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.height
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.widget.dialog.BaseBottomSheetFragment
import com.starblink.basic.ext.screenHeight
import com.starblink.basic.util.KeyboardUtils
import com.starblink.library.widget.databinding.DialogSubsEmailInputBinding

/**
 * 订阅消息，email输入
 *  Create by yuanl at 2023/10/7
 **/
class SubsEmailInputDF(private val dialogHeight:Int?=null) : BaseBottomSheetFragment() {

    private val binding by lazy {
        DialogSubsEmailInputBinding.inflate(layoutInflater)
    }

    private val vm by createViewModelLazy(SubsVM::class, {
        this.viewModelStore
    })

    private var email: String? = null

    var success: (()-> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        email = arguments?.getString("email")
    }

    override fun getBindingRootView(): View = binding.root

    override fun initView() {
        //vm.loadAccountInfo()

        if (dialogHeight != null) {
            binding.llEmailDialog.height(dialogHeight)
        } else {
            binding.llEmailDialog.height(ViewGroup.LayoutParams.WRAP_CONTENT)
            binding.vDividerMain.updateLayoutParams<LinearLayout.LayoutParams> {
                height = 124.dp
                weight = 0f
            }
        }

        show2Btn(UserDataCenter.isLogin().not() && email.isNullOrEmpty())

        if (email?.isNotEmpty() == true) {
            setFillEmail()
        }

        binding.btnClose.setOnClickListener {
            dismissNow()
        }
        binding.btnConfirm.setOnClickListener {
            vm.bindSubsEmail(binding.input.editText?.text?.toString() ?: "")
        }
        binding.btnFill.setOnClickListener {
            if (UserDataCenter.isLogin().not()) {
                LoginCheckInterceptor.check2Login(requireContext()) {
                    //setFillEmail()
                    vm.fetchSubsEmail()
                }
            } else {
                setFillEmail()
            }
//            setFillEmail()
        }
        binding.root.setOnClickListener {
            KeyboardUtils.closeSoftKeyboard(it)
        }

        vm.bindEmailLD.observe(this) {
            if (it) {
                UserDataCenter.putSubscribeEmial(binding.input.editText?.text?.toString() ?: "")
                dismissNow()
                success?.invoke()
            }
        }

        vm.loadEmailLD.observe(this) {
            email = it
            show2Btn(email?.isNotEmpty() == true)
            setFillEmail()
        }
    }

    private fun setFillEmail() {
        binding.input.editText?.run {
            setText(email)
            setSelection(text.length)
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                window?.setDecorFitsSystemWindows(false)
                window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
            } else {
                window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
            }
            ViewCompat.setWindowInsetsAnimationCallback(
                window!!.decorView,
                object : WindowInsetsAnimationCompat.Callback(
                    DISPATCH_MODE_STOP
                ) {
                    override fun onProgress(
                        insets: WindowInsetsCompat,
                        runningAnimations: MutableList<WindowInsetsAnimationCompat>
                    ): WindowInsetsCompat {
                        val isVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
                        val keyboardH = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom

                        // simple handle, TODO  accurate
                        val baseTransY = -keyboardH.toFloat() * 0.5f
                        window?.decorView?.findViewById<View>(android.R.id.content)?.translationY = baseTransY
                        binding.layoutBtns.translationY = if (binding.vDividerMain.height > 124.dp) baseTransY else baseTransY * 0.5f
                        return insets
                    }
                })
        }
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.decorView?.findViewById<View>(android.R.id.content)?.translationY = 0F
        binding.layoutBtns.translationY = 0F
        KeyboardUtils.closeSoftKeyboard(binding.root)
    }

    private fun show2Btn(yes: Boolean) {
        if (yes) {
            binding.btnFill.visible()
            binding.btnDiv.visible()
        } else {
            binding.btnConfirm.setBackgroundResource(com.starblink.android.basic.R.drawable.sp_sd_dark1_r)
        }
    }

}